package com.cloud_sang.entity;

import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @ClassTitle: JsoupTest
 * @ProjectName springcould2020
 * @Description: jsoup网页抓取
 * @Author Sangsang
 * @Date 2020/9/30
 * @Time 15:45
 */

/*
  <!-- https://mvnrepository.com/artifact/cn.hutool/hutool-all -->
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.1.0</version>
        </dependency>

        <dependency>
            <groupId>org.jsoup</groupId>
            <artifactId>jsoup</artifactId>
            <version>1.11.3</version>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.17</version>
        </dependency>

*/


public class JsoupTest {
	public static void main(String[] args) throws IOException {

		Map<String, String> requestParams = new HashMap<String, String>();
		ArrayList<Map<String, Object>> rows = new ArrayList<>();

		for (int j = 0; j < 154; j++) {
			Document doc = Jsoup.connect("http://home.oa.gyzq.com//pagepublish/CommunicationPage.aspx").data(requestParams).post();
			requestParams.put("__VIEWSTATE", doc.body().getElementById("__VIEWSTATE").val());
			requestParams.put("__VIEWSTATEGENERATOR", "5BE5AC0D");
			requestParams.put("__EVENTVALIDATION", doc.body().getElementById("__EVENTVALIDATION").val());
			requestParams.put("nextButton.x", "1");
			requestParams.put("nextButton.y", "1");

			Elements listgrid = doc.body().getElementsByClass("listgrid");
			for (Element element : listgrid) {
				Elements tr = element.getElementsByTag("tr");
				for (Element element1 : tr) {
					Elements td = element1.getElementsByTag("td");
					//System.out.println(td.toString());
					Map<String, Object> row1 = new LinkedHashMap<>();
					for (int i = 0; i < td.size(); i++) {
						switch (i) {
							case 0:
								row1.put("姓名", td.eq(i).text());
								break;
							case 1:
								row1.put("电话", td.eq(i).text());
								break;
							case 2:
								row1.put("手机号码", td.eq(i).text());
								break;
							case 3:
								row1.put("邮件地址", td.eq(i).text());
								break;
							case 4:
								row1.put("所属部门", td.eq(i).text());
								rows.add(row1);
								break;
							default:
								//th = "未知错误~";
						}
					}
				}
			}
		}
		ExcelWriter(rows);

	}
	public static void ExcelWriter(ArrayList<Map<String, Object>> rows) {
		ExcelWriter writer = ExcelUtil.getWriter("C:/Users/Administrator/Desktop/国元证券人员名单.xlsx");
		// 合并单元格后的标题行，使用默认标题样式
		writer.write(rows, true);
		// 关闭writer，释放内存
		writer.close();
	}
}
